<?php


namespace Modules\Common\Lib\FeiShu;
use Illuminate\Support\Facades\Cache;

class SendMessages extends Base
{
    public function index(array $data){
        $tenantAccessTokenInfo = Cache::get('FeiShuTenantAccessToken'.$this->app_id);
        if(!$tenantAccessTokenInfo){
            $tenantAccessTokenInfo = $this->getTenantAccessToken();
            if($tenantAccessTokenInfo['code'] !== 0){
                return ['code'=>0,'message'=>json_encode($tenantAccessTokenInfo)];
            }
            if($tenantAccessTokenInfo['expire']>600){
                Cache::put('FeiShuTenantAccessToken'.$this->app_id,json_encode($tenantAccessTokenInfo),($tenantAccessTokenInfo['expire']-600));
            }
        }else{
            $tenantAccessTokenInfo = json_decode($tenantAccessTokenInfo,true);
        }
        $tenant_access_token = 'Bearer ' . $tenantAccessTokenInfo['tenant_access_token'];
        $batchGetIdInfo = $this->batchGetId($data['mobiles'],$tenant_access_token);
        if($batchGetIdInfo['code'] !== 0){
            return ['code'=>0,'message'=>json_encode($batchGetIdInfo)];
        }
        if(!isset($batchGetIdInfo['data']) || !isset($batchGetIdInfo['data']['mobile_users']) || !isset($batchGetIdInfo['data']['mobile_users'][$data['mobiles']]) || !isset($batchGetIdInfo['data']['mobile_users'][$data['mobiles']][0]) || !isset($batchGetIdInfo['data']['mobile_users'][$data['mobiles']][0]['open_id'])){
            return ['code'=>0,'message'=>'用户信息不存在'];
        }
        $res = $this->sendMsg($batchGetIdInfo['data']['mobile_users'][$data['mobiles']][0]['open_id'],$tenant_access_token,$data);
        if($res['code'] != 0){
            return ['code'=>0,'message'=>json_encode($res)];
        }
        return ['code'=>1,'发送成功！'];
    }
    private function sendMsg(string $openId,string $tenant_access_token,array $data){
        $url = 'https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id';
        $res = $this->httpRequest($url,json_encode([
            "receive_id"=>$openId,
            "content"=>isset($data['content'])?$data['content']:json_encode(["text"=>"没有发消息"]),
            "msg_type"=>isset($data['msg_type'])?$data['msg_type']:'text'
        ]),false,[
            "Authorization:".$tenant_access_token,
            "Content-Type:application/json;charset=utf-8"
        ]);
        return json_decode($res['body'],true);
    }
    private function batchGetId(string $mobiles,string $tenant_access_token){
        $url = 'https://open.feishu.cn/open-apis/user/v1/batch_get_id?mobiles='.$mobiles;
        $res = $this->httpRequest($url,null,false,[
            "Authorization:".$tenant_access_token,
            "Content-Type:application/json;charset=utf-8"
        ]);
        return json_decode($res['body'],true);
    }
}
